package com.my.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * @功能
 * @创建时间 2020/3/8
 */
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        Iterator<ConfigAttribute> iterator = collection.iterator();
        System.err.println(iterator.hasNext()+"111");
        while (iterator.hasNext()){
            ConfigAttribute ca = iterator.next();
            String needRole = ca.getAttribute();
            System.err.println(needRole);
            if("ROLE_LOGIN".equals(needRole)){
                System.out.println(authentication instanceof AnonymousAuthenticationToken);
                System.out.println(authentication.getAuthorities());
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new BadCredentialsException("未登录");
                }else
                    return;
                }
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

                    for (GrantedAuthority authority : authorities){
                        if(authority.getAuthority().equals(needRole)){
                            return;
                        }
                    }

            }
            throw new AccessDeniedException("权限不足");
        }




    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
